/**
 * 兼容 有的机型是全量ID
 * @param id 
 * @param ms 
 * @returns 
 */
export function getElementById(id: string, ms: number = 5000) {
    const node = selector().idContains(id).findOne(ms)
    return node;
}

export function getElementByIdMatches() { }

export function getVisibleElementById(id: string, ms: number = 5000) {
    return selector().idContains(id).visibleToUser(true).findOne(ms)
}

export function getVisibleElementByText(text: string, ms: number = 5000) {
    return selector().textContains(text).visibleToUser(true).findOne(ms)
}

export function getCurrentPackageName() {
    return selector().visibleToUser(true).findOne().packageName()
}

export function getCurrentPackageNameBy(name: string) {
    return selector().visibleToUser(true).packageName(name).findOne(3000).packageName()
}

export function getCurrentPackage() {
    return selector().visibleToUser(true).findOne()?.packageName()
}

export function launchPackage(name: string) {
    return app.launchPackage(name)
}

export const PACKAGES = {
    [`com.smile.gifmaker`]: `com.smile.gifmaker`,
    [`com.kuaishou.nebula`]: `com.kuaishou.nebula`
}

export function waitForElementById(id: string) {
    return selector().idContains(id).waitFor()
}

export function swipeUp() {
    const scrollableNode = selector().scrollable().findOne()
    if (scrollableNode) {
        // 导入AutoJS依赖
        const height = device.height;
        const width = device.width;
        // 模拟上划操作
        swipe(width / 2, height * 4 / 5, width / 2, height / 10, 300);
        return;
    }
    throw new Error(`没有scrollable元素，向上滑动失败`)
}

export class ElementNotFound {
    message: string;
    constructor(msg: string) {
        this.message = msg;
    }
}

export function clickButton(btn: UiObject) {
    if (!btn) throw new ElementNotFound(`按钮不能为空`)
    if (btn.clickable()) {
        return btn.click()
    } else {
        const bounds = btn.bounds();
        click(bounds.centerX(), bounds.centerY());
        return true;
    }
}

export function tryClickButton(button: UiObject, time: number = 3000) {
    try {
        clickButton(button)
        sleep(time)
        return true;
    } catch (e) {
        return false;
    }
}

export function tryClickButtonUtil(button: UiObject, time: number = 3000) {
    try {
        while (!clickButton(button)) {
            sleep(1000)
        }
        sleep(time)
        return true;
    } catch (e) {
        return false;
    }
}

export function setText(ele: UiObject, text: string) {
    if (!ele) throw new ElementNotFound(`输入框不能为空`)
    ele.setText(text)
}


/**
 * 等待快手打开
 */
export function waitForPackage(name: string) {
    let pkg = selector().findOne(3000)?.packageName();
    while (pkg !== name) {
        pkg = selector().findOne(3000)?.packageName();
        sleep(1000)
    }
    return true;
}
